const tbody = document.querySelector('tbody');
function studentList() {
    axios({
        url: '/student/list',
        method: 'get',
    }).then((res) => {
        if (res.data.code === 0) {
            // toastr.success(res.data.message)
            const listContent = res.data.data.map(item => `<tr>
            <th scope="row">${item.id}</th>
            <td>${item.name}</td>
            <td>${item.age}</td>
            <td>${item.sex}</td>
            <td>${item.group}</td>
            <td>${item.phone}</td>
            <td>${item.salary}</td>
            <td>${item.truesalary}</td>
            <td>${item.province + item.city + item.county}</td>
            <td>
              <button type="button" class="btn btn-primary btn-sm" data-id="${item.id}">修改</button>
              <button type="button" class="btn btn-danger btn-sm" data-id="${item.id}">删除</button>
            </td>
          </tr>`)
            tbody.innerHTML = listContent;
        } else {
            toastr.warning(res.data.message)
        }
        // console.log( res)
    })
}
studentList()

function ajaxWeb(url, params, text, selectDom, value="") {
    axios({
        url,
        method: 'get',
        params,
    }).then((res) => {
        const html = res.data.map(item => `<option value="${item}">${item}</option>`)
        selectDom.innerHTML = `<option selected value="">--${text}--</option>` + html.join('')
        selectDom.value = value;
        // console.log( res)
    })
}

const addModel = document.querySelector('#addModal')

// debugger
function initSelect(parent) {
    const ProvinceSelect = document.querySelector(`.${parent} [name=province]`);
    const CitySelect = document.querySelector(`.${parent} [name=city]`);
    const countySelect = document.querySelector(`.${parent} [name=county]`);

    ajaxWeb('/geo/province', {}, '省', ProvinceSelect)

    ProvinceSelect.addEventListener('change', function () {
        countySelect.innerHTML = `<option>--县--</option>`
        if(!ProvinceSelect.value) {
            CitySelect.innerHTML = `<option>--市--</option>`
            return
        }
        ajaxWeb('/geo/city', {
            pname: ProvinceSelect.value,
        }, '市', CitySelect, value="")
    })

    CitySelect.addEventListener('change', function () {
        if(!CitySelect.value) {
            countySelect.innerHTML = `<option>--县--</option>`
            return
        }
        ajaxWeb('/geo/county', {
            pname: ProvinceSelect.value,
            cname: CitySelect.value,
        }, '县', countySelect);
    })
}
initSelect('add-form')
initSelect('update-form')

// 新增事件
{
    const addForm = addModel.querySelector(".add-form")
    addForm.addEventListener('submit', function (e) {
        e.preventDefault();
        const data = $(this).serialize();
        console.log(data)
        axios({
            url: '/student/add',
            method: 'POST',
            data,
        }).then((res) => {
            if (res.data.code === 0) {
                toastr.success(res.data.message, "消息提示");
                studentList();
                $('#addModal').modal('hide');
                addForm.reset();
            } else {
                toastr.warning(res.data.message, "消息提示");
            }
        })
    })

    const addStuInfo = document.querySelector( '[data-class=addStuInfo]')
    addStuInfo.addEventListener( 'click', function(e) {
        addForm.reset();
        const CitySelect = addForm.querySelector(`[name=city]`);
        const countySelect = addForm.querySelector(`[name=county]`);
        CitySelect.innerHTML = `<option>--市--</option>`;
        countySelect.innerHTML = `<option>--县--</option>`;
        $(addModel).modal('show')
    })
}

// 删除与修改事件
{
    const updateForm = document.querySelector('.update-form');
    tbody.addEventListener('click', function (e) {
        if (e.target.classList.contains('btn-danger')) {
            axios({
                url: '/student/delete',
                method: 'DELETE',
                params: e.target.dataset,
            }).then((res) => {
                if (res.data.code === 0) {
                    toastr.success(res.data.message, "消息提示")
                    studentList()
                } else {
                    toastr.warning(res.data.message, "消息提示")
                }
                // console.log(res)
            })
        } else if (e.target.classList.contains('btn-primary')) {
            $('#updateModal').modal('show')
            axios({
                url: '/student/one',
                method: 'get',
                params: e.target.dataset,
            }).then(({ data: { data } }) => {
                // 获取的数据输入updateForm之中
                for (const key in data) {
                    // const dom = updateForm.querySelector(`[name=${key}]`)
                    const dom = document.querySelector(`.update-form [name=${key}]`)
                    if (dom && dom.name !== "sex") {
                        dom.value = data[key]
                    }
                }
                // 单选框先选name，再选value（精髓！！！）
                updateForm.querySelector(`[name=sex][value=${data.sex}]`).checked = true;
                ajaxWeb('/geo/city', { pname:data.province,}, '市', updateForm.querySelector(`[name=city]`), data.city);
                ajaxWeb('/geo/county', { pname:data.province, cname:data.city,}, '县', updateForm.querySelector('[name=county]'), data.county);
            })
        }
    })

    updateForm.addEventListener( 'submit', function(e) {
        e.preventDefault();
        const data = $(updateForm).serialize();
        axios({
            url:'/student/update',
            method:'put',
            data,
        }).then( (res) => {
            if( res.data.code === 0) {
                toastr.success( res.data.message, "消息提示");
                $('#updateModal').modal('hide');
                studentList()
            } else {
                toastr.warning( res.data.message, "消息提示");
            }
            // console.log( res)
        });
    })
}